package util;

import java.sql.Connection;

/*
 * DbUtil类：建立数据库链接
 * 
 * 
 * */

import java.sql.DriverManager;

public class DbUtil {
	private static String dbUrl="jdbc:mysql://localhost:3306/db_food?useUnicode=true&characterEncoding=utf8";	//保证MySql的gdk编码能与Java的utf8编码一致
	private static String dbUserName="root";
	private static String dbPassword="lipanke203201";
	private static String jdbcName="com.mysql.cj.jdbc.Driver";
//	registerDriver
	/**
	 * 获取connection
	 * @return
	 * @throws Exception
	 */
	public static Connection getCon() throws Exception{				//获取数据库链接
		Class.forName(jdbcName);								//注册驱动
		Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);		//获取数据库操作对象
		return con;
	}
	
	/**
	 * 关闭connection
	 * @param con
	 * @throws Exception
	 */
	public void closeCon(Connection con) throws Exception{
		if(con!=null){
			con.close();
		}
	}

	public static void main(String[] args) {
		DbUtil dbUtil=new DbUtil();
		try {
			dbUtil.getCon();
			System.out.println("获取connection成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("获取失败");
		}
	}
}
